<template>
  <div class="login">
    <Navbar></Navbar>

    <van-row justify="center">
      <van-col span="10">
        <h3>开始准备好好学习</h3>
      </van-col>
    </van-row>
    <van-row justify="center">
      <van-col span="10">
        <p>好好学习，做前端达人</p>
      </van-col>
    </van-row>

    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="username"
          name="username"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>

    <van-row justify="center">
      <van-col span="10">
        <router-link to="/register">没有账号, 请点击注册</router-link>
      </van-col>
    </van-row>

    <Tabbar></Tabbar>
  </div>
</template>

<script setup>
import Navbar from "@/components/Navbar.vue";
import Tabbar from "@/components/Tabbar.vue";
import { ref } from "vue";
import axios from "axios";
import { showSuccessToast, showFailToast } from 'vant';
import { useRouter } from 'vue-router';

const username = ref("");
const password = ref("");
const router = useRouter();

function onSubmit() {
  axios.get("http://localhost:3000/users?username=" + username.value).then((result) => {
    // 验证用户密码是否正确
    if(result.data.length === 1) {
      if(result.data[0].password === password.value) {
        // 登录成功
        sessionStorage.setItem("username", username.value);
        showSuccessToast('登录成功');
        router.push("/mine");
      } else {
        // 密码错误
        showFailToast("密码错误");
      }
    }
  });
}
</script>

<style scoped>
</style>